/**
 *  @author: zhangxt
 *  @date:2023/02/28
 *  @description: 全局工具类
 */

const repair = i => {
  return i < 10 ? '0' + i : i
}

/**
 * 获取当前日期（默认）、时间、星期
 * type：date、time、week
 * sub：相差天数，-1前一天 1后一天
 * time：时间基准
 */
function getNow(type, sub, time) {
  let str, date, y, M, d, H, m, s, w
  if (!time) {
    date = new Date()
  } else {
    date = new Date(time)
  }
  if (sub) {
    date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * sub)
  }
  y = date.getFullYear()
  M = repair(date.getMonth() + 1)
  d = repair(date.getDate())
  H = repair(date.getHours())
  m = repair(date.getMinutes())
  s = repair(date.getSeconds())
  w = date.getDay()
  switch (type) {
    case 'week':
      str = '星期' + '日一二三四五六'.charAt(w)
      break
    case 'time':
      str = `${y}-${M}-${d} ${H}:${m}:${s}`
      break
    default:
      str = `${y}-${M}-${d}`
      break
  }
  return str
}

/**
 * 切换月份
 * type：prev（上一个月）、next（下一个月）
 * time: 时间基准
 */
function getMonth(type, time) {
  if (!time) {
    time = getNow()
  }
  if (!type) {
    return time
  }
  let [y, M, d] = time.split('-')
  if (type === 'prev') {
    M = parseInt(M) - 1
    if (M === 0) {
      y = parseInt(y) - 1
      M = 12
    }
  }
  if (type === 'next') {
    M = parseInt(M) + 1
    if (M === 13) {
      y = parseInt(y) + 1
      M = 1
    }
  }
  let max = new Date(y, M, d).getDate() //获取当前日期中的月的天数
  if (d > max) {
    d = max
  }
  if (M < 10) {
    M = '0' + M
  }
  return `${y}-${M}-${d}`
}

/**
 * 多久之前
 */
function getAgo(time) {
  if (!time) return
  let date = Date.now() - new Date(time).getTime()
  if (date < 0) {
    return time
  }
  let y, M, d, H, m, s, k, v
  s = Math.floor(date / 1000)
  m = Math.floor(s / 60)
  H = Math.floor(m / 60)
  d = Math.floor(H / 24)
  M = Math.floor(d / 30)
  y = Math.floor(M / 12)
  if (y > 0) {
    k = 'y'
    v = y
  } else if (M > 0) {
    k = 'M'
    v = M
  } else if (d > 0) {
    k = 'd'
    v = d
  } else if (H > 0) {
    k = 'H'
    v = H
  } else if (m > 0) {
    k = 'm'
    v = m
  } else {
    k = 's'
    v = s || 1
  }
  let temp = {
    y: '%n% 年前',
    M: '%n% 个月前',
    d: '%n% 天前',
    H: '%n% 小时前',
    m: '%n% 分钟前',
    s: '%n% 秒前'
  }
  return temp[k].replace('%n%', v)
}

/**
 * @description 对象转url参数
 * @param {object} data,对象
 * @param {Boolean} isPrefix,是否自动加上"?"
 * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
 */
export function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
  const prefix = isPrefix ? '?' : ''
  const _result = []
  if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) === -1) {
    arrayFormat = 'brackets'
  }
  for (const key in data) {
    const value = data[key]
    // 去掉为空的参数
    if (['', undefined, null].indexOf(value) >= 0) {
      continue
    }
    // 如果值为数组，另行处理
    if (value.constructor === Array) {
      let commaStr = ''
      // e.g. {ids: [1, 2, 3]}
      switch (arrayFormat) {
        case 'indices':
          // 结果: ids[0]=1&ids[1]=2&ids[2]=3
          for (let i = 0; i < value.length; i++) {
            _result.push(`${key}[${i}]=${value[i]}`)
          }
          break
        case 'brackets':
          // 结果: ids[]=1&ids[]=2&ids[]=3
          value.forEach(_value => {
            _result.push(`${key}[]=${_value}`)
          })
          break
        case 'repeat':
          // 结果: ids=1&ids=2&ids=3
          value.forEach(_value => {
            _result.push(`${key}=${_value}`)
          })
          break
        case 'comma':
          // 结果: ids=1,2,3
          value.forEach(_value => {
            commaStr += (commaStr ? ',' : '') + _value
          })
          _result.push(`${key}=${commaStr}`)
          break
        default:
          value.forEach(_value => {
            _result.push(`${key}[]=${_value}`)
          })
      }
    } else {
      _result.push(`${key}=${value}`)
    }
  }
  return _result.length ? prefix + _result.join('&') : ''
}

// 获取所有字典项
function getCodeList(dictType) {
  let codeList = JSON.parse(sessionStorage.getItem('dictionary'))
  return codeList.filter(item => item.dictType === dictType)
}

// 字典项匹配
function getCodeLabel(dictType, dictValue) {
  let codeList = JSON.parse(sessionStorage.getItem('dictionary'))
  let filterCode = codeList.filter(
    item => item.dictType === dictType && item.dictValue === dictValue
  )
  return filterCode && filterCode.length !== 0 ? filterCode[0].dictLabel : ''
}

export default {
  getNow,
  getMonth,
  getAgo,
  queryParams,
  getCodeList,
  getCodeLabel
}
